#!/bin/sh
#
# $Header: mkinitramfs-ll/scripts/xcpio                  Exp $
# $Author: (c) 2011-2015 -tclover <tokiclover@gmail.com> Exp $
# $License: 2-clause/new/simplified BSD                  Exp $
# $Version: 2015/01/20 12:33:03                          Exp $
#

usage() {
	cat <<-EOH
usage: xcpio [options] files
  -l, --list        list files
  -x, --extract     extract files
  -d, --decompress  decompress files
EOH
exit
}

[ "$#" = 0 ] && usage

comp() {
	local comp
	case "$2" in
		(*.bz*2) comp='bzip2 -d -k'  ;;
		(*.gz*)  comp='gzip -d'      ;;
		(*.xz|*.lzma) comp='xz -d -k';;
		(*.lzo*) comp='lzop -d -k'   ;;
		(*.lz4)  comp='lz4 -d'       ;;
		(*.lz*)  comp='lzip -d -k'   ;;
		(*) echo "xcpio: unsupported compression format"
		    exit 2;;
	esac
	$comp $@
}

case "$1" in
	(-l|--list)    opt=-t
		shift;;
	(-x|-*xtract)  opt=-id
		shift;;
	(-d|*compress) opt=
		shift;;
	(*)            opt=-t;;
esac

for file in $*; do
	if [ -f "$file" ]; then
		tmpdir=${file##*/}
		tmpdir=$(mktemp -d ${tmpdir%.cpio*}-XXXXXX)
		cd $tmpdir || exit $?
		if [ -n "$opt" ]; then
			comp "-c" "$file" | cpio $opt -v
		else
			comp "$file"
		fi
		[ "$?" = 0 ] && echo "xcpio: successfuly deflated to $tmpdir" ||
			echo "xcpio: failed to process file"
	else
		echo "xcpio: $file file not found"
	fi
done

unset -v file opt pipe tmpdir

#
# vim:fenc=utf-8:ci:pi:sts=0:sw=4:ts=4:
#
